<template>
  <div class="writeScene">
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/sensorHome' }" class="homePage">传感器类型管理</el-breadcrumb-item>
        <el-breadcrumb-item>编辑</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <div class="title">编辑传感器类型管理</div>
    <div class="main">
      <div class="header">
        <span></span>
        <p>传感器信息</p>
      </div>
      <div class="mainFrom">
        <el-form
          :model="addSensorParams"
          :rules="rules"
          ref="addSensorParams"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item prop="sceneTypeName" label="传感器类型名称 :" class="sensorTypeName">
            <el-input v-model="addSensorParams.sceneTypeName" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item prop="sensorType" label="监测类型名称 :" class="sensorType">
            <el-input v-model="addSensorParams.sensorType" maxlength="10"></el-input>
          </el-form-item>
          <div class="itemImg">传感器图标 :</div>
          <el-form-item prop="imageList" class="imgItem">
            <el-upload
              :action="uploadImg"
              list-type="picture-card"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers="headOfRequest"
              :with-credentials="true"
              :limit="1"
              :file-list="addSensorParams.imageList"
              ref="elUpload"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>
          <el-form-item label="设备描述 :" class="deviceTypeDesc">
            <el-input
              type="textarea"
              placeholder="请输入设备描述"
              v-model="addSensorParams.deviceTypeDesc"
              maxlength="50"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <footer>
        <div class="title">
          <div class="left">
            <span></span>
            <p>传感器监测数据管理</p>
          </div>
          <div class="addSensorInfo" @click="addBox">添加</div>
        </div>
        <table class="dataInfo" border="0" cellspacing="0" cellpadding="0">
          <thead class="dataHead">
            <th>数据名称</th>
            <th>单位</th>
            <th>键值</th>
            <th>操作</th>
          </thead>
          <tbody class="dataBody" v-show="deviceTable.length !== 0">
            <tr v-for="(item, index) in deviceTable" :key="index">
              <td>{{ item.natureValue }}</td>
              <td>{{ item.natureUnit }}</td>
              <td>{{ item.natureKey }}</td>
              <td>
                <span class="write" @click="writeMonitor(item, index)">编辑</span>
                <span class="delete" @click="deleteDeviceMonitor(item, index)">删除</span>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="emptyTbody" v-show="deviceTable.length === 0">暂无数据</div>
        <!-- 导航栏 -->
        <div class="block" v-if="deviceTable.length !== 0">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="5000"
            layout="total, prev, pager, next, jumper"
            :total="deviceTable.length"
          ></el-pagination>
        </div>
        <span class="addOne" v-show="isAddOne">请添加至少一个传感器监测数据</span>
        <div class="determain">
          <div class="btn" @click="determainAddDevice">确定</div>
        </div>
      </footer>
      <!-- 添加盒子 -->
      <div
        class="addbox"
        v-if="
          this.$store.state.sensor.showAddBox && this.$store.state.ifShowCover
        "
      >
        <div class="boxHeader">
          <p>添加设备监测数据</p>
          <i class="el-icon-close" @click="closeAddBox"></i>
        </div>
        <div class="addMainBox">
          <el-form
            :model="deviceMonitorList"
            :rules="rules"
            ref="deviceMonitorList"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item prop="natureValue" label="数据名称 :" class="name">
              <el-input v-model="deviceMonitorList.natureValue" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item prop="natureUnit" label="单位 :" class="unit">
              <el-input v-model="deviceMonitorList.natureUnit"></el-input>
            </el-form-item>
            <el-form-item prop="natureKey" label="键值 :" class="associateKey">
              <el-input v-model="deviceMonitorList.natureKey"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <footer>
          <div class="cancel" @click="closeAddBox">取消</div>
          <div class="determainAdd" @click="determainAdd">确定</div>
        </footer>
      </div>
      <!-- 删除盒子 -->
      <div class="deleteBox" v-if="this.$store.state.showDelete && this.$store.state.ifShowCover">
        <div class="deleteMain">
          <div class="title">
            <p>删除</p>
            <i class="el-icon-close" @click="closeDeleteBox"></i>
          </div>
          <div class="main">
            <div>
              <p class="determine">确定删除“{{ deviceTypeName }}”监测数据？</p>
            </div>
          </div>
          <div class="btn">
            <div>
              <div class="cancel" @click="closeDeleteBox">取消</div>
              <div class="deterMine" @click="deleteDeviceType">确定</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 编辑盒子 -->
      <div
        class="addbox"
        v-if="
          this.$store.state.sensor.showWriteBox && this.$store.state.ifShowCover
        "
      >
        <div class="boxHeader">
          <p>编辑设备监测数据</p>
          <i class="el-icon-close" @click="closeAddBox"></i>
        </div>
        <div class="addMainBox">
          <el-form
            :model="writeParams"
            :rules="rules"
            ref="writeParams"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item prop="natureValue" label="数据名称 :" class="name">
              <el-input v-model="writeParams.natureValue" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item prop="natureUnit" label="单位 :" class="unit">
              <el-input v-model="writeParams.natureUnit" maxlength="10"></el-input>
            </el-form-item>
            <el-form-item prop="natureKey" label="键值 :" class="associateKey">
              <el-input v-model="writeParams.natureKey" maxlength="10"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <footer>
          <div class="cancel" @click="closeAddBox">取消</div>
          <div class="determainAdd" @click="determainWrite">确定</div>
        </footer>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadImg, deleteImg } from '../../../api/file'
import { getToken } from '../../../utils/token'
import { getDeviceByid, writeDviceType } from '../../../api/sensor'
export default {
  data () {
    return {
      // 上传图片的url地址
      uploadImg: uploadImg,
      // 上传图片组件的请求头设置
      headOfRequest: { token: getToken() },
      addSensorParams: {
        sceneTypeName: '',
        sensorType: '',
        imageList: [],
        deviceTypeDesc: '',
        imageUrl: ''
      },
      deviceMonitorList: {
        natureKey: '',
        natureUnit: '',
        natureValue: '',
        deviceTypeId: '',
        natureId: ''
      },
      deviceTable: [],
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        sceneTypeName: [
          { required: true, message: '请输入传感器类型名称', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '长度需小于20个字符',
            trigger: ['blur', 'change']
          }
        ],
        sensorType: [
          { required: true, message: '请输入监测类型名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        imageList: [
          { required: true, message: '请输入数据名称', trigger: 'blur' }
        ],
        natureValue: [
          { required: true, message: '请输入数据名称' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        natureUnit: [
          { required: true, message: '请输入单位' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        natureKey: [
          { required: true, message: '请输入键值' },
          {
            min: 1,
            max: 10,
            message: '长度需小于10个字符',
            trigger: ['blur', 'change']
          }
        ],
        isShow: [{ required: true, message: '请选择' }]
      },
      currentPage: +'',
      isAddOne: false,
      deviceTypeName: '',
      deleteMonitorId: '',
      writeParams: [],
      WriteIndex: ''
    }
  },
  computed: {
    writeId () {
      return sessionStorage.getItem('id')
    }
  },
  methods: {
    beforeUpload (file) {
      const testmsg = /^image\/(jpg|JPG|jpeg|png|PNG|bmp|BMP)$/.test(file.type)
      const isLT3M = file.size / 1024 / 1024 <= 3
      if (!testmsg) {
        this.$message.error('图片格式错误')
        return false
      }
      if (!isLT3M) {
        this.$message.error('上传图片大小不能超过3M!')
        return false
      }
      return testmsg && isLT3M
    },
    // 图片上传成功的钩子
    handleSuccess (res, file, fileList) {
      const arr = this.$refs.elUpload.$children[1].$el.classList
      arr.add('hidden')
      this.addSensorParams.imageList.push({ name: res.data.fileName, url: res.data.url })
      this.addSensorParams.imageUrl = res.data.url
    },
    // 图片移除成功的钩子
    handleRemove (file, fileList) {
      // console.log(file)
      const arr = this.$refs.elUpload.$children[1].$el.classList
      arr.remove('hidden')
      this.addSensorParams.imageList = []
      deleteImg(12, file.url)
    },
    // 查看大图的钩子
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleCurrentChange (val) {
      // // console.log(val)
    },
    addBox () {
      this.$store.state.ifShowCover = true
      this.$store.commit('sensor/show_addBox', true)
    },
    closeAddBox () {
      this.$store.state.ifShowCover = false
      this.$store.commit('sensor/show_addBox', false)
    },
    // 根据id获取设备类型
    async getDeviceByid () {
      const { data: res } = await getDeviceByid(this.writeId)
      // console.log(res)
      this.addSensorParams.sceneTypeName = res.data.deviceTypeName
      this.addSensorParams.sensorType = res.data.deviceCheckType
      const url = await this.$_makeMediaSrc(Number(res.data.deviceTypeImg))
      // console.log(url)
      this.addSensorParams.imageList.push({ name: res.data.deviceTypeName, url: url })
      this.addSensorParams.deviceTypeDesc = res.data.deviceTypeDesc
      this.deviceTable = res.data.deviceMonitorList
      this.addSensorParams.imageUrl = res.data.deviceTypeImg
    },
    determainAdd () {
      this.isAddOne = false
      this.$refs.deviceMonitorList.validate(valid => {
        if (valid) {
          this.deviceTable.push(this.deviceMonitorList)
          this.$store.state.ifShowCover = false
          this.$store.commit('sensor/show_addBox', false)
          this.deviceMonitorList = {}
        }
      })
    },
    // 确定编辑
    determainWrite () {
      this.$refs.writeParams.validate(valid => {
        if (valid) {
          this.deviceTable[this.WriteIndex] = this.writeParams
          this.$store.state.ifShowCover = false
          this.$store.commit('sensor/show_writeBox', false)
        }
      })
    },
    async determainAddDevice () {
      if (this.deviceTable.length === 0) {
        this.isAddOne = true
        return
      }
      this.$refs.addSensorParams.validate(valid => {
        if (valid) {
          const params = {
            deviceCheckType: this.addSensorParams.sensorType,
            deviceMonitorList: this.deviceTable,
            deviceTypeDesc: this.addSensorParams.deviceTypeDesc,
            deviceTypeImg: this.addSensorParams.imageUrl,
            deviceTypeName: this.addSensorParams.sceneTypeName
          }
          writeDviceType(params, this.writeId).then(res => {
            if (res.data.code === 200) {
              this.$message({
                message: res.data.message,
                type: 'success',
                duration: 1000
              })
              this.$router.push('/sensorHome')
            } else {
              this.$message({
                message: res.data.message,
                type: 'error',
                duration: 1500
              })
            }
          })
        }
      })
    },
    deleteDeviceMonitor (item, index) {
      // console.log(item)
      this.deviceTypeName = item.natureValue
      this.deleteMonitorId = index
      this.$store.state.showDelete = true
      this.$store.state.ifShowCover = true
    },
    closeDeleteBox () {
      this.$store.state.showDelete = false
      this.$store.state.ifShowCover = false
    },
    async deleteDeviceType () {
      // console.log(this.deleteMonitorId)
      this.deviceTable.splice(this.deleteMonitorId, 1)
      this.$store.state.showDelete = false
      this.$store.state.ifShowCover = false
    },
    writeMonitor (item, index) {
      this.WriteIndex = index
      this.writeParams = { ...item }
      this.$store.state.ifShowCover = true
      this.$store.commit('sensor/show_writeBox', true)
      this.$store.commit('sensor/show_addBox', false)
    }
  },
  created () {
    this.getDeviceByid()
  },
  mounted () {
    if (this.addSensorParams.imageList) {
      const arr = this.$refs.elUpload.$children[1].$el.classList
      arr.add('hidden')
    }
  }
}
</script>

<style lang="scss" scoped>
.deleteBox {
  position: fixed;
  top: 180px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 999;
  width: 560px;
  height: 360px;
  background: rgba(255, 255, 255, 1);
  border-radius: 5px;
}
@import "../../../styles/sensor.scss";
@import "../../../styles/writeBox.scss";
@import "../../../styles/deleteBox.scss";
  table {
    position: relative;
    margin-top: 20px;
    width: 96%;
    text-align: left;
      thead.dataHead {
        font-weight: 500;
        font-size: 14px;
        background: rgba(87, 131, 255, 0.05);
        th {
          color: rgba(51, 51, 51, 1);
          height: 60px;
          line-height: 60px;
          text-align: left;
          padding-left: 24px;
          border-bottom: solid 1px rgba(230, 230, 230, 1);
        }
      }
    tbody {
      tr {
        height: 64px;
        td {
          font-size: 14px;
          font-weight: 400;
          color: rgba(102, 102, 102, 1);
          padding-left: 24px;
          border-bottom: solid 1px #f2f2f2;
          .write {
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            color: rgba(72, 104, 255, 1);
            text-decoration: underline;
          }
          .delete {
            cursor: pointer;
            margin-left: 24px;
            font-size: 14px;
            font-weight: 500;
            color: #fb4646;
            text-decoration: underline;
          }
        }
      }
    }
  }
</style>
